import { httpRequest } from '../httpRequest'
import _ from 'lodash';

async function createDataStore(tifpath) {
  console.log(tifpath);
  const workspace = 'test_tif';
  const storeName = tifpath.split('/').pop().split(".")[0];
  const filePath = `file:///${tifpath}`; // 注意路径前要加上 file://

  let geoserverUrl = '/geoserver/rest'

  const xml = `
    <coverageStore>
      <name>${storeName}</name>
      <type>org.geoserver.coverage2d.store.GeoTIFFCoverageStore</type>
      <parameters>
        <entry key="url">file:///${tifpath}</entry>
      </parameters>
      <enabled>true</enabled>
    </coverageStore>
  `;

  try {
    const response = await httpRequest.post(
      `${geoserverUrl}/workspaces/${workspace}/coveragestores`,
      xml,
      {
        headers: {
          'Content-Type': 'application/xml',
          'Authorization': 'Basic YWRtaW46Z2Vvc2VydmVy',
        },
      }
    );

    console.log('数据存储创建成功:', response.data);
  } catch (error) {
    console.error('创建数据存储失败:', error.response?.data || error.message);
  }
}

async function createLayer(tifpath) {
  const workspace = 'test_tif';
  const storeName = tifpath.split('/').pop().split(".")[0];
  const layerName = tifpath;

  let geoserverUrl = '/geoserver/rest'

  const xml = `
    <layer>
      <name>${layerName}</name>
      <title>TIF Coverage Layer</title>
      <type>org.geoserver.coverage2d.type.GeoTIFFCoverageType</type>
      <coverageStore>
        <name>${storeName}</name>
      </coverageStore>
      <srs>
        <srsName>EPSG:4326</srsName>
      </srs>
      <maxScaleDenominator>1e9</maxScaleDenominator>
      <minScaleDenominator>0</minScaleDenominator>
      <Queryable>true</Queryable>
      <Visible>true</Visible>
    </layer>
  `;

  try {
    const response = await httpRequest.post(
      `${geoserverUrl}/workspaces/${workspace}/coveragestores`,
      xml,
      {
        headers: {
          'Content-Type': 'application/xml',
          'Authorization': 'Basic YWRtaW46Z2Vvc2VydmVy',
        },
      }
    );

    console.log('图层发布成功:', response.data);
  } catch (error) {
    console.error('发布图层失败:', error.response?.data || error.message);
  }
}



export default {

  // 下载文件接口

  getdownload(filepath) {
    return httpRequest.get(`/api/download?file=${encodeURIComponent(filepath)}`, {}, {
      responseType: 'blob'
    })

  },

  // 打开文件选择器
  getOpenfile(dirpath) {
    return httpRequest.get(`/api/openfile`,)
  },

  // 读取文件目录
  getDirList(dirpath) {
    return httpRequest.get(`/api/dirimglist?dirpath=${dirpath}`,)
  },

  // 提交文件夹扫描记录
  submitdir(params) {
    return httpRequest.post(`/api/submitdir`, params)
  },

  // 获取所有监控文件夹
  getdirlist() {
    return httpRequest.get(`/api/getdirlist`,)
  },

  // 清空所有数据
  emptyimglist() {
    return httpRequest.get(`/api/emptyimglist`,)
  },

  // 获取列表数据分页
  // maxFeatures
  // startIndex
  // sortBy
  getYingxiangList(params) {
    return httpRequest.get(`/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=test_tif:Imglists&outputFormat=application%2Fjson`, { params })
  },


  // 生成wms服务接口
  genWmsService(params) {
    // return axios.put(`/geoserver/rest/workspaces/test_tif/coveragestores/wwwww/external.geotiff`,

    return new Promise((resolve, reject) => {
      createDataStore(params.tifpath)
      createLayer(params.tifpath)
      resolve()
    })

    // 使用 coverstores创建
    // return httpRequest.put(
    //   `/geoserver/rest/workspaces/test_tif/coveragestores/${params.layername}/external.geotiff`,
    //   'file:///' + params.tifpath,
    //   {
    //     headers: {
    //       'Content-Type': 'text/plain',
    //       Authorization: 'Basic YWRtaW46Z2Vvc2VydmVy',
    //     },
    //   },
    // )
  },
}